package com.xxl.job.executor.service.manage;


import com.web.all.common.bean.response.Result;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;
import com.xxl.job.executor.mvc.api.ManageApi;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * 用户相关定时任务
 *
 * @author zhangchongyang
 */
@JobHandler(value = "ManageJobHandler")
@Component
@Log4j2
public class ManageJobHandler extends IJobHandler {

    private final ManageApi manageApi;

    @Autowired
    public ManageJobHandler(ManageApi manageApi) {
        this.manageApi = manageApi;
    }

    @Override
    public ReturnT<String> execute(String param) {
        XxlJobLogger.log("ManageJobHandler, 同步钉钉部门成功. 参数{}", param);
        log.info("ManageJobHandler, 同步钉钉部门成功. 参数{}", param);
        try {
            Result result = manageApi.autoSaveOrganization();
            if (result.isSuccess()) {
                XxlJobLogger.log("ManageJobHandler, 同步新增/修改部门成功. 参数{}", param);
                log.info("ManageJobHandler, 同步新增/修改部门成功. 参数{}", param);
            }
            result = manageApi.autoSaveUser();
            if (result.isSuccess()) {
                XxlJobLogger.log("ManageJobHandler, 同步新增/修改用户成功. 参数{}", param);
                log.info("ManageJobHandler, 同步新增/修改用户成功. 参数{}", param);
            }
            result = manageApi.autoDeleteUser();
            if (result.isSuccess()) {
                XxlJobLogger.log("ManageJobHandler, 同步删除用户成功. 参数{}", param);
                log.info("ManageJobHandler, 同步删除用户成功. 参数{}", param);
            }
            result = manageApi.autoDeleteOrganization();
            if (result.isSuccess()) {
                XxlJobLogger.log("ManageJobHandler, 同步删除部门成功. 参数{}", param);
                log.info("ManageJobHandler, 同步删除部门成功. 参数{}", param);
            }
            XxlJobLogger.log("ManageJobHandler, 同步钉钉部门用户. 参数{}", param);
            log.error("ManageJobHandler, 同步钉钉部门用户. 参数:{}，原因：{}", param, result.getMsg());
            return SUCCESS;
        } catch (Exception e) {
            log.error("ManageJobHandler, 同步钉钉部门用户. 参数{}，原因：{}", param, e.getMessage());
            return FAIL;
        }
    }
}
